package com.quanyan.stadium.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.quanyan.api.APIResponse;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.stadium.api.req.*;
import com.quanyan.stadium.api.resp.RespInitEvaluate;
import com.quanyan.stadium.api.resp.RespLocation;
import com.quanyan.stadium.api.resp.RespUserRadarChart;
import com.quanyan.stadium.biz.redis.UserGameScheduleCacheDao;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.constants.RadarChartConstants;
import com.quanyan.stadium.entity.*;
import com.quanyan.stadium.entity.vo.*;
import com.quanyan.stadium.enums.RadarChartEnum;
import com.quanyan.stadium.mapper.TbRadarChartDescMapper;
import com.quanyan.stadium.mapper.TbRadarChartMapper;
import com.quanyan.stadium.mapper.TbUserGameScheduleMapper;
import com.quanyan.stadium.service.commonComponent.BaseService;
import com.quanyan.stadium.service.GradeIntegralService;
import com.quanyan.stadium.service.commonComponent.OfficialGameCache;
import com.quanyan.stadium.service.RadarChartService;
import com.quanyan.stadium.utils.StringUtils;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserTaskServiceFacade;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@Service
public class RadarChartServiceImpl implements RadarChartService {

    private static final String STADIUM_RADAR_CHART_REDISKEY = "STADIUM_RADAR_CHART";
    private static final String RADAR_CHART_STADIUM_PREFIX = "RADAR_CHART_STADIUM_TYPE$";

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    TbRadarChartDescMapper radarChartDescMapper;

    @Autowired
    TbRadarChartMapper radarChartMapper;

    @Autowired
    private GradeIntegralService gradeIntegralService;

    @Autowired
    TbUserGameScheduleMapper userGameScheduleMapper;

    @Autowired
    GradeIntegralService integralService;

    @Autowired
    private QcMsgClient qcMsgClient;

    @Autowired
    UserTaskServiceFacade userTaskServiceFacade;

    @Autowired
    BaseService baseService;

    @Autowired
    UserGameScheduleCacheDao userGameScheduleCacheDao;


    @Autowired
    ClubOpenService clubOpenService;


    @Autowired
    OfficialGameCache officialGameCache;

    public static final Logger logger = LoggerFactory.getLogger("RadarChartServiceImpl");

    public Map<String, BaseRadarChart> initRadarChart() {
        ObjectMapper mapper = new ObjectMapper();
        Integer[] type = {GameConstants.CATEGORY_ID_FOOTBALL, GameConstants.CATEGORY_ID_BASKETBALL,
            GameConstants.CATEGORY_ID_TENNIS, GameConstants.CATEGORY_ID_BADMINTON};
        List<Integer> stadiumType = Arrays.asList(type);
        TbRadarChartDescExample radarChartDescExample = new TbRadarChartDescExample();
        TbRadarChartDescExample.Criteria criteria = radarChartDescExample.createCriteria();
        criteria.andTypeIn(stadiumType);
        criteria.andIsDelteEqualTo(GameConstants.IS_NOT_DELETE);
        List<TbRadarChartDesc> tbRadarChartDescs =
            radarChartDescMapper.selectByExample(radarChartDescExample);
        Map<String, BaseRadarChart> map = Maps.newHashMap();
        for (TbRadarChartDesc tbRadarChartDesc : tbRadarChartDescs) {
            String radarChartKey =
                RADAR_CHART_STADIUM_PREFIX.concat(Integer.toString(tbRadarChartDesc.getType()));
            BaseRadarChart baseRadarChart = new BaseRadarChart();
            baseRadarChart.setId(tbRadarChartDesc.getId());
            baseRadarChart.setType(tbRadarChartDesc.getType());
            baseRadarChart.setSpace(tbRadarChartDesc.getSpace());
            baseRadarChart.setMaxLength(tbRadarChartDesc.getMaxLength());
            baseRadarChart.setPointCount(tbRadarChartDesc.getPointCount());
            baseRadarChart.setWaveLevel(tbRadarChartDesc.getWaveLevel());
            try {
                String jsonStr = tbRadarChartDesc.getRadarchart();
                List<RadarItems> myObjects = mapper.readValue(jsonStr,
                    mapper.getTypeFactory().constructCollectionType(List.class, RadarItems.class));
                baseRadarChart.setItems(myObjects);
                jsonStr = tbRadarChartDesc.getSelfEvalPercent();
                List<SelfEvalute> selfEvalutes = mapper.readValue(jsonStr,
                    mapper.getTypeFactory().constructCollectionType(List.class, SelfEvalute.class));
                baseRadarChart.setSelfEvalutes(selfEvalutes);
                if(tbRadarChartDesc.getType() == 1 || tbRadarChartDesc.getType() == 3){
                    jsonStr = tbRadarChartDesc.getLocation();
                    Map<String, String> location = mapper.readValue(jsonStr, new TypeReference<Map<String, String>>() { });
                    baseRadarChart.setLocation(location);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            map.put(radarChartKey, baseRadarChart);
        }
        return map;
    }

    /**
     * 获取雷达图基本数据
     *
     * @return
     */
    public Map<String, BaseRadarChart> getBaseRadarChart() {

        Map<String, BaseRadarChart> map = null;
        RedisKey rk = new RedisKey(RedisConstants.STADIUM_FAMILY_KEY, STADIUM_RADAR_CHART_REDISKEY);
        Object o = redisTemplate.get(rk);
        Optional<Object> optional = Optional.fromNullable(o);
        if (optional.isPresent()) {
            map = (Map<String, BaseRadarChart>) o;
        } else {
            map = initRadarChart();
            redisTemplate.setWithExpireTime(rk, map, GameConstants.RADAR_CHART_REDIS_EXPIRE_TIME);
        }
        return map;
    }



    @Override public RespUserRadarChart userRadarChart(ReqUserRadarChart request) {
        Optional<RespUserRadarChart> o = userRadarChart(request.getType(), request.getUid());
        return o.get();
    }

    @Override
    public List<RespUserRadarChart> queryUserRadarChartBatch(ReqUserRadarChartBatch request) {
        List<RespUserRadarChart> list = Lists.newArrayList();
        for(Integer i:request.getUids()){
            RespUserRadarChart respUserRadarChart = userRadarChart(request.getType(),i).get();
            list.add(respUserRadarChart);
        }
        return list;
    }

    @Override
    public APIResponse selfEvaluate(ReqRadarSelfEvaluate request) {
        // 1234 对于篮 羽 足 网
        if(request.getType() == 1 || request.getType() == 3){
            if(request.getLocation() == null){
                return APIResponse.returnFail("足球和篮球位置不能为空！");
            }
        }
        Map<String, BaseRadarChart> map = getBaseRadarChart();
        RespUserRadarChart respUserRadarChart = null;
        BaseRadarChart baseRadarChart =
            map.get(RADAR_CHART_STADIUM_PREFIX.concat(Integer.toString(request.getType())));
        Optional<BaseRadarChart> chartOptional = Optional.fromNullable(baseRadarChart);
        if (chartOptional.isPresent()) {
            Double percent = 0D;
            List<SelfEvalute> selfEvalutes = baseRadarChart.getSelfEvalutes();
            List<RadarItems> radarItemses = baseRadarChart.getItems();
            for (SelfEvalute selfEvalute : selfEvalutes) {
                if (selfEvalute.getType().equals(request.getLevel())) {
                    percent = selfEvalute.getPercent();
                    break;
                }
            }
            TbRadarChartExample tbRadarChartExample = new TbRadarChartExample();
            TbRadarChartExample.Criteria criteria = tbRadarChartExample.createCriteria();
            criteria.andTypeEqualTo(request.getType().byteValue());
            criteria.andUidEqualTo(request.getUid());
            criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
            List<TbRadarChart> tbRadarCharts =
                radarChartMapper.selectByExample(tbRadarChartExample);
            if (tbRadarCharts != null && tbRadarCharts.size() > 0) {
                return APIResponse.returnFail("用户已经有雷达数据，无法自评！");
            } else {
                TbRadarChart chart = new TbRadarChart();
                chart.setUid(request.getUid());
                chart.setType(request.getType().byteValue());
                chart.setIsDelete((byte) 0);
                chart.setLevel(request.getLevel());
                if(request.getType().equals(GameConstants.CATEGORY_ID_FOOTBALL) || request.getType().equals(GameConstants.CATEGORY_ID_BASKETBALL)){
                    chart.setLocation(request.getLocation());
                }
                //位置！
                Double[] location = {1d,1d,1d,1d,1d,1d,1d};
                if(request.getType() == 1 || request.getType() == 3){
                    String locationStr = baseRadarChart.getLocation().get(request.getLocation().toString());
                    location = strToDoubleArray(locationStr);
                }
                for (int i = 1; i <= baseRadarChart.getPointCount(); i++) {
                    Class clazz = chart.getClass();
                    try {
                        double pointInitVal =
                            radarItemses.get(i - 1).getInitValue().doubleValue() * percent * location[i - 1 ];
                        //四舍五入，保留两位小数
                        BigDecimal b = new BigDecimal(pointInitVal);
                        pointInitVal = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        Method method =
                            clazz.getMethod("setCategory".concat(String.valueOf(i)), Double.class);
                        method.invoke(chart, pointInitVal);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                radarChartMapper.insert(chart);
            }
        }
        return APIResponse.returnSuccess("用户初始化自评成功！");
    }

    /**
     *
     * @param str
     * @return
     */
    protected Double[] strToDoubleArray(String str){
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        String array[] = str.split(",");
        Double darray[] = new Double[array.length];
        for (int i = 0; i < array.length; i++) {
            darray[i] = Double.parseDouble(array[i]);
        }
        return darray;
    }


    /*protected Optional<RespUserRadarChart> userRadarChart(Integer type, Integer uid) {
        Map<String, BaseRadarChart> map = getBaseRadarChart();
        RespUserRadarChart respUserRadarChart = null;
        BaseRadarChart baseRadarChart =
            map.get(RADAR_CHART_STADIUM_PREFIX.concat(Integer.toString(type)));
        Optional<BaseRadarChart> chartOptional = Optional.fromNullable(baseRadarChart);
        if (chartOptional.isPresent()) {
            //然后查询个人数据
            TbRadarChartExample tbRadarChartExample = new TbRadarChartExample();
            TbRadarChartExample.Criteria criteria = tbRadarChartExample.createCriteria();
            criteria.andUidEqualTo(uid);
            criteria.andTypeEqualTo(type.byteValue());
            criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
            List<TbRadarChart> radarCharts = radarChartMapper.selectByExample(tbRadarChartExample);
            if (CollectionUtils.isEmpty(radarCharts)) {
                //用户没数据，初始化自评
                ReqRadarSelfEvaluate reqRadarSelfEvaluate = new ReqRadarSelfEvaluate();
                reqRadarSelfEvaluate.setLevel(3);
                reqRadarSelfEvaluate.setUid(uid);
                reqRadarSelfEvaluate.setType(type);
                reqRadarSelfEvaluate.setLocation(1);
                selfEvaluate(reqRadarSelfEvaluate);
                radarCharts = radarChartMapper.selectByExample(tbRadarChartExample);
            }
                TbRadarChart radarChart = radarCharts.get(0);
                respUserRadarChart = new RespUserRadarChart();
                BeanUtils.copyProperties(baseRadarChart, respUserRadarChart);
                List<UserRadarItem> userRadarItems = Lists.newArrayList();
                List<RadarItems> radarItems = baseRadarChart.getItems();
                Integer level = radarChart.getLevel();
                Integer location = radarChart.getLocation();
                respUserRadarChart.setLocation(location);
                respUserRadarChart.setLevel(level);
                if (type == GameConstants.CATEGORY_ID_FOOTBALL || type == GameConstants.CATEGORY_ID_BASKETBALL) {
                    if (type == GameConstants.CATEGORY_ID_FOOTBALL) {
                        respUserRadarChart.setLocationName(RadarChartConstants.FootBallConstants
                            .getNameByType(radarChart.getLocation()));
                    } else {
                        respUserRadarChart.setLocationName(RadarChartConstants.BasketBallConstants
                            .getNameByType(radarChart.getLocation()));
                    }
                }
                for (int i = 1; i <= baseRadarChart.getPointCount(); i++) {
                    Class clazz = TbRadarChart.class;
                    try {
                        Method method =
                            clazz.getMethod("getCategory".concat(Integer.valueOf(i).toString()));
                        Object o = method.invoke(radarChart);
                        Double radarChartVal = 0D;
                        if (Optional.fromNullable(o).isPresent()) {
                            radarChartVal = (Double) o;
                        }
                        UserRadarItem userItem = new UserRadarItem();
                        userItem.setPointValue(radarChartVal);
                        BeanUtils.copyProperties(radarItems.get(i - 1), userItem);
                        if(type == GameConstants.CATEGORY_ID_TENNIS){
                            double val = userItem.getPointValue();
                            long number = (long) val;
                            double demicel = val - (long)val;
                            if(demicel > 0.5){
                                val = number + 1;
                            }else if(demicel > 0 && demicel < 0.5){
                                val = number + 0.5;
                            }
                            userItem.setPointValue(val);
                        }
                        userRadarItems.add(userItem);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }
                respUserRadarChart.setUserItems(userRadarItems);
            }
        return Optional.fromNullable(respUserRadarChart);
    }*/

    protected Optional<RespUserRadarChart> userRadarChart(Integer type, Integer uid) {
        Map<String, BaseRadarChart> map = getBaseRadarChart();
        RespUserRadarChart respUserRadarChart = null;
        BaseRadarChart baseRadarChart =
            map.get(RADAR_CHART_STADIUM_PREFIX.concat(Integer.toString(type)));
        Optional<BaseRadarChart> chartOptional = Optional.fromNullable(baseRadarChart);
        if (chartOptional.isPresent()) {
            //然后查询个人数据
            TbRadarChartExample tbRadarChartExample = new TbRadarChartExample();
            TbRadarChartExample.Criteria criteria = tbRadarChartExample.createCriteria();
            criteria.andUidEqualTo(uid);
            criteria.andTypeEqualTo(type.byteValue());
            criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
            List<TbRadarChart> radarCharts = radarChartMapper.selectByExample(tbRadarChartExample);
            if (!CollectionUtils.isEmpty(radarCharts)) {
                TbRadarChart radarChart = radarCharts.get(0);
                respUserRadarChart = new RespUserRadarChart();
                BeanUtils.copyProperties(baseRadarChart, respUserRadarChart);
                List<UserRadarItem> userRadarItems = Lists.newArrayList();
                List<RadarItems> radarItems = baseRadarChart.getItems();
                Integer level = radarChart.getLevel();
                Integer location = radarChart.getLocation();
                respUserRadarChart.setLocation(location);
                respUserRadarChart.setLevel(level);
                if (type == GameConstants.CATEGORY_ID_FOOTBALL || type == GameConstants.CATEGORY_ID_BASKETBALL) {
                    if (type == GameConstants.CATEGORY_ID_FOOTBALL) {
                        respUserRadarChart.setLocationName(RadarChartConstants.FootBallConstants
                            .getNameByType(radarChart.getLocation()));
                    } else {
                        respUserRadarChart.setLocationName(RadarChartConstants.BasketBallConstants
                            .getNameByType(radarChart.getLocation()));
                    }
                }
                for (int i = 1; i <= baseRadarChart.getPointCount(); i++) {
                    Class clazz = TbRadarChart.class;
                    try {
                        Method method =
                            clazz.getMethod("getCategory".concat(Integer.valueOf(i).toString()));
                        Object o = method.invoke(radarChart);
                        Double radarChartVal = 0D;
                        if (Optional.fromNullable(o).isPresent()) {
                            radarChartVal = (Double) o;
                        }
                        UserRadarItem userItem = new UserRadarItem();
                        userItem.setPointValue(radarChartVal);
                        BeanUtils.copyProperties(radarItems.get(i - 1), userItem);
                        if(type == GameConstants.CATEGORY_ID_TENNIS){
                            double val = userItem.getPointValue();
                            long number = (long) val;
                            double demicel = val - (long)val;
                            if(demicel > 0.5){
                                val = number + 1;
                            }else{
                                val = number + 0.5;
                            }
                            userItem.setPointValue(val);
                        }
                        userRadarItems.add(userItem);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }
                respUserRadarChart.setUserItems(userRadarItems);
            }else{
                respUserRadarChart = new RespUserRadarChart();
                BeanUtils.copyProperties(baseRadarChart, respUserRadarChart);
                List<RadarItems> radarItems = baseRadarChart.getItems();
                List<UserRadarItem> userRadarItems = Lists.newArrayList();
                for (int i = 1; i <= baseRadarChart.getPointCount(); i++) {
                    UserRadarItem userItem = new UserRadarItem();
                    userItem.setPointValue(0d);
                    BeanUtils.copyProperties(radarItems.get(i - 1), userItem);

                    userRadarItems.add(userItem);

                }
                respUserRadarChart.setUserItems(userRadarItems);
            }
        }
        return Optional.fromNullable(respUserRadarChart);
    }


    //获得某一个节点的雷达能力
    protected Double oneRadarValue(Double recentRadarVal, Integer Type,
        Double levelScoreRange) {
        BigDecimal ratio = null;
        BigDecimal ratioWeight = null;
        BigDecimal recentRadar = BigDecimal.valueOf(recentRadarVal);
        BigDecimal levelScoreCount = BigDecimal.valueOf(levelScoreRange);
        switch (Type) {
            case 1:
                ratio = BigDecimal.valueOf(RadarChartEnum.BASKETBALL_RADAR_CHART_TYPE.getRatio());
                ratioWeight =
                    BigDecimal.valueOf(RadarChartEnum.BASKETBALL_RADAR_CHART_TYPE.getRatioWeight());
                break;
            case 2:
                ratio = BigDecimal.valueOf(RadarChartEnum.BADMINTON_RADAR_CHART_TYPE.getRatio());
                ratioWeight =
                    BigDecimal.valueOf(RadarChartEnum.BADMINTON_RADAR_CHART_TYPE.getRatioWeight());
                break;
            case 3:
                ratio = BigDecimal.valueOf(RadarChartEnum.FOOTBALL_RADAR_CHART_TYPE.getRatio());
                ratioWeight =
                    BigDecimal.valueOf(RadarChartEnum.FOOTBALL_RADAR_CHART_TYPE.getRatioWeight());
                break;
            case 4:

                ratio = BigDecimal.valueOf(RadarChartEnum.BASEBALL_RADAR_CHART_TYPE.getRatio());
                ratioWeight =
                    BigDecimal.valueOf(RadarChartEnum.BASEBALL_RADAR_CHART_TYPE.getRatioWeight());
                break;
        }
        BigDecimal radarScore = levelScoreCount.divide(RadarChartConstants.dividNum)
            .multiply(RadarChartConstants.percentNum).multiply(ratio);
        BigDecimal ratioWeightLeft = BigDecimal.valueOf(1D).subtract(ratioWeight);
        radarScore.multiply(ratioWeight).add(recentRadar).multiply(ratioWeightLeft);
        return radarScore.doubleValue();
    }




    protected void updateUserRadarChart(Integer uid,Integer type,Double scoreRange){
        Optional<RespUserRadarChart> optional =  userRadarChart(uid,type);
        if(optional.isPresent()){
            //更新这个用户的雷达图数据
            TbRadarChart tbRadarChart = new TbRadarChart();
            tbRadarChart.setUid(uid);
            RespUserRadarChart userRadarChart = optional.get();
            List<UserRadarItem> userRadarItems = userRadarChart.getUserItems();
            Class clazz = tbRadarChart.getClass();
            for (int i = 0; i < userRadarChart.getPointCount(); i++) {
                Double bigDecimal = oneRadarValue(userRadarItems.get(i).getPointValue(),type,scoreRange);
                try {
                    Method method = clazz.getMethod("setCategory".concat(Integer.valueOf(i + i).toString()),Double.class);
                    method.invoke(tbRadarChart,bigDecimal);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            TbRadarChartExample example = new TbRadarChartExample();
            TbRadarChartExample.Criteria criteria = example.createCriteria();
            criteria.andUidEqualTo(uid);
            criteria.andTypeEqualTo(type.byteValue());
            criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
            radarChartMapper.updateByExampleSelective(tbRadarChart,example);
        }
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse commitUserRadarChart(ReqEvaluateGame request) {
        //更新评价状态
        TbUserGameScheduleExample example1 = new TbUserGameScheduleExample();
        TbUserGameScheduleExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andUidEqualTo(request.getUid());
        criteria1.andGameScheduleIdEqualTo(request.getGameScheduleId());
        TbUserGameSchedule tbUserGameSchedule = new TbUserGameSchedule();
        tbUserGameSchedule.setIsAccess((byte) 1);
        userGameScheduleMapper.updateByExampleSelective(tbUserGameSchedule,example1);
        if(request.getType().intValue() == 1 || request.getType().intValue() == 3){
            try {
                officialGameCache.updateGameSchedule(request.getGameScheduleId(), (byte) 1);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }else{
            try {
                officialGameCache.updateGameSchedule(request.getGameScheduleId(), (byte) 0);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        //刷新用户记录状态
        userGameScheduleCacheDao.delUserGameRecordSetInterval(request.getUid());

        //String cachePrefix = "UserRadarChart";
        List<EvaluateScore> list = request.getEvaluate();
        if (CollectionUtils.isEmpty(list)) {
            return APIResponse.returnFail("null commitData!");
        }
        for (EvaluateScore score : request.getEvaluate()) {
            ReqUserRadarChart reqUserRadarChart = new ReqUserRadarChart();
            reqUserRadarChart.setType(request.getType());
            reqUserRadarChart.setUid(score.getId());
            Boolean flag = checkRadarData(reqUserRadarChart).getData();
            if(!flag){
                //没有雷达图数据，跳过
                continue;
            }
            Optional<RespUserRadarChart> o = userRadarChart(request.getType(), score.getId());
            if (!o.isPresent()) {
                continue;
            } else {
                RespUserRadarChart respRadarChart = o.get();
                TbRadarChart radarChart = new TbRadarChart();
                Class clazz = TbRadarChart.class;
                Method method = null;
                for (int i = 0; i < respRadarChart.getPointCount(); i++) {
                    try {
                         method =
                            clazz.getMethod("setCategory".concat(String.valueOf(i+1)), Double.class);
                    } catch (NoSuchMethodException e) {//异常不需要处理，直接跳过！
                    }
                    double initVal = respRadarChart.getUserItems().get(i).getInitValue();
                    double pointVal = respRadarChart.getUserItems().get(i).getPointValue();
                    double percent = 0;
                    try {
                        percent = pointVal / initVal;
                    } catch (Exception e1) {}//异常不需要处理，直接跳过！

                            double scoreVal = score.getEvaluateScore().get(i).getValue() - 0.5;
                                percent = percent + Math.random() * RadarChartConstants.RATIO * scoreVal;
                            if (percent >= 1.05 ) {
                                percent = 1.05;
                            }
                            if(percent <= 0){
                                percent = 0.05;
                            }
                            pointVal = initVal * percent;
                            DecimalFormat df = new DecimalFormat("#.###");
                            pointVal = Double.parseDouble(df.format(pointVal));
                            try {
                                method.invoke(radarChart,pointVal);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                        }
                    }
                TbRadarChartExample example = new TbRadarChartExample();
                TbRadarChartExample.Criteria criteria = example.createCriteria();
                criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
                criteria.andTypeEqualTo(request.getType().byteValue());
                criteria.andUidEqualTo(score.getId());
                radarChartMapper.updateByExampleSelective(radarChart,example);
            }
        }
        /**
         * 任务中心发送消息
         */
        try {
            MqRequestMsg mqRequestMsg = new MqRequestMsg();
            mqRequestMsg.setTopic(Constants.MQ_TOPIC_TASK_TOPIC);
            mqRequestMsg.setTag(Constants.MQ_TOPIC_TASK_TAG);
            mqRequestMsg.setFlag(0);
            UserTaskMsg userTaskMsg = new UserTaskMsg();
            userTaskMsg.setUid(request.getUid());
            userTaskMsg.setTaskId(TaskEnum.TASK_ENUM__COMMENT_OPPONENT.getId());

            mqRequestMsg.setBody(ObjectUtil.toByteArray(userTaskMsg));
            qcMsgClient.asyncSend(mqRequestMsg);
        } catch (Exception e) {
            logger.error("任务中心发送消息失败！");
        }
        return  APIResponse.returnSuccess("评价成功！");
    }

    @Override public APIResponse evaluateGame(ReqEvaluateGame request) {

        ReqQuaryIntegral reqQuaryIntegral = new ReqQuaryIntegral();
        reqQuaryIntegral.setGameId(reqQuaryIntegral.getGameId());
        reqQuaryIntegral.setUserId(request.getUid());
        //Integer result = gradeIntegralService.getIntegral(reqQuaryIntegral);
        Optional<RespUserRadarChart> optional =  userRadarChart(request.getType(),request.getUid());
        if(optional.isPresent()){
            ///RespRadarChart respRadarChart = optional.get();

        }else{
            return APIResponse.returnFail("该用户没有雷达数据,无法评价!");
        }

        /*
       // RespRadarChart radarChart = userRadarChart(request.getType(), request.getUid());
        RespRadarChart respRadarChartResult = new RespRadarChart();
        //上限
        //RadarChartInitValue RadarChartInitValue =
        //  radarChart.getBaseRadarChart().getRadarChartInitValue();
        for (int i = 0; i < radarChart.getBaseRadarChart().getPointCount(); i++) {
            try {
                Method radarMethod = RespRadarChart.class
                    .getMethod("getCategory".concat(Integer.valueOf(i).toString()));
                Method initValMethod = RespRadarChart.class
                    .getMethod("getCategory".concat(Integer.valueOf(i).toString()));
                Double val = (Double) radarMethod.invoke(radarChart, null);
                //  Double topVal = (Double) initValMethod.invoke(RadarChartInitValue, null);
                Double socreRange = 120D;
                BigDecimal oneRadarValue = oneRadarValue(val, request.getType(), socreRange);
                //  Double radarAbility =
                //    oneRadarValue.multiply(BigDecimal.valueOf(topVal)).doubleValue();
                //Method resultMethod = RespRadarChart.class
                //     .getMethod("setCategory".concat(Integer.valueOf(i).toString()));
                //  resultMethod.invoke(respRadarChartResult, radarAbility);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            //入库
            TbRadarChart tbRadarChart = new TbRadarChart();
            BeanUtils.copyProperties(respRadarChartResult, tbRadarChart);
            TbRadarChartExample radarChartExample = new TbRadarChartExample();
            TbRadarChartExample.Criteria criteria = radarChartExample.createCriteria();
            criteria.andUidEqualTo(request.getUid());
            criteria.andTypeEqualTo(request.getType().byteValue());
            radarChartMapper.updateByExample(tbRadarChart, radarChartExample);
        }*/
        return null;
    }

    @Override public APIResponse<RespInitEvaluate> initEvaluation(ReqInitEvaluate request) {
        //拿到雷达图基本数据
        String radarChartKey =
            RADAR_CHART_STADIUM_PREFIX.concat(Integer.toString(request.getType()));
        BaseRadarChart baseRadarChart = getBaseRadarChart().get(radarChartKey);
        RespInitEvaluate respInitEvaluate = new RespInitEvaluate();
        respInitEvaluate.setType(baseRadarChart.getType());
        respInitEvaluate.setMaxLength(baseRadarChart.getMaxLength());
        respInitEvaluate.setSpace(baseRadarChart.getSpace());
        respInitEvaluate.setItems(baseRadarChart.getItems());
        return APIResponse.returnSuccess(respInitEvaluate);
    }

    @Override
    public APIResponse<RespLocation> evaluationLevel(ReqUserRadarChart request) {
        RespLocation respLocation = new RespLocation();
        List<Location> list = Lists.newArrayList();
        if(request.getType().equals(1)){
            list.add(new Location(1,"前锋"));
            list.add(new Location(2,"中场/前腰"));
            list.add(new Location(3,"后卫/后腰"));
            list.add(new Location(4,"门将"));
        }
        if(request.getType().equals(2)){
            list.add(new Location(1,"中锋"));
            list.add(new Location(2,"大前锋"));
            list.add(new Location(3,"小前锋"));
            list.add(new Location(4,"控球后卫"));
            list.add(new Location(5,"得分后卫"));
        }
        respLocation.setLocation(list);
        return APIResponse.returnSuccess(respLocation);
    }

    @Override
    public void updateGameRadarChart(UpdateGameRadar request) {
        Optional<RespUserRadarChart> o = userRadarChart(request.getType(),request.getUid());
        if(!o.isPresent()){
            return ;
        }else{
            RespUserRadarChart userRadarChart = o.get();
            List<UserRadarItem> radarItemses = userRadarChart.getUserItems();
            TbRadarChart tbRadarChart = new TbRadarChart();
            for (int i = 1; i <= userRadarChart.getPointCount(); i++) {
                Class clazz = TbRadarChart.class;
                try {
                    double pointVal = radarItemses.get(i - 1).getPointValue().doubleValue();
                    double initVal = radarItemses.get(i - 1).getInitValue().doubleValue();
                    double percent = pointVal / initVal;
                    Double ratio = 0.01;
                    Double win = 0d;
                    switch (request.getGameType()) {
                        case 0:
                            ratio = RadarChartConstants.OFFICE_RATIO_GAME;
                            break;
                        case 1:
                            ratio = RadarChartConstants.OPPOINT_RATIO_GAME;
                            break;
                        case 2:
                            ratio = RadarChartConstants.PK_RATIO_GAME;
                            break;
                        default:
                            ratio = 0.01;
                            break;
                    }

                    switch (request.getIsWin()) {
                        case -1:
                            win = RadarChartConstants.EQUAL;
                            break;
                        case 1:
                            win = RadarChartConstants.WIN;
                            break;
                        case 0:
                            win = RadarChartConstants.FAIL;
                            break;
                        default:
                            ratio = 0d;
                            break;
                    }

                    double percentChange =percent + win * Math.random() * ratio * 0.2;
                    if(percentChange >= 1.05){
                        percentChange = 1.05;
                    }
                    if(percentChange <= 0){
                        percentChange = 0.01;
                    }
                    double pointInitVal = percentChange * initVal;
                    Method method =
                        clazz.getMethod("setCategory".concat(String.valueOf(i)), Double.class);
                    method.invoke(tbRadarChart, pointInitVal);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            TbRadarChartExample example = new TbRadarChartExample();
            TbRadarChartExample.Criteria criteria = example.createCriteria();
            criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
            criteria.andTypeEqualTo(request.getType().byteValue());
            criteria.andUidEqualTo(request.getUid());
            radarChartMapper.updateByExampleSelective(tbRadarChart,example);
        }
    }



    @Override
    public APIResponse<Boolean> checkRadarData(ReqUserRadarChart request) {
        TbRadarChartExample example = new TbRadarChartExample();
        TbRadarChartExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(request.getUid());
        criteria.andTypeEqualTo(request.getType().byteValue());
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        List<TbRadarChart> list = radarChartMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            return APIResponse.returnSuccess(false);
        }else{
            return APIResponse.returnSuccess(true);
        }
    }

    @Override
    public APIResponse<List<User>> commitUserList(ReqCommitUser request) {
        TbUserGameScheduleExample example = new TbUserGameScheduleExample();
        TbUserGameScheduleExample.Criteria criteria = example.createCriteria();
        criteria.andGameScheduleIdEqualTo(request.getGameScheduleId());
        List<TbUserGameSchedule> list = userGameScheduleMapper.selectByExample(example);
        List<User> users = Lists.newArrayList();
        for (TbUserGameSchedule tbUserGameSchedule : list) {
            if (tbUserGameSchedule.getUid().equals(request.getUid()))
                continue;
            RespUserInfoBase userInfoBase = baseService.queryUserMsg(tbUserGameSchedule.getUid());
            User user = new User();
            user.setUid(userInfoBase.getUid());
            user.setNickName(userInfoBase.getNickName());
            user.setIcon(userInfoBase.getIcon());
            users.add(user);
        }
        return APIResponse.returnSuccess(users);
    }
}
